package com.juyu.reader.author.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.CharsetUtils;
import org.apache.http.util.EntityUtils;

import com.juyu.reader.author.model.Book;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class HttpToPost extends HttpServlet {

	public String doPost(InputStream in, String filename,HttpServletRequest request) throws Exception {
		String imgPath="";
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost("http://resource.sxyd8.com/srvapifile/user/uploadFile");
		httpPost.setHeader("systemId", "resource");
		httpPost.setHeader("projectId", "P201704051440251503135");
		String timestamp = StringUtil.getTimestamp();
		httpPost.setHeader("timestamp", timestamp);
		httpPost.setHeader("secretId", "NjdjNDcx");
		httpPost.setHeader("version", "1.0.0");
		httpPost.setHeader("platform", "2");
		String randomKey = StringUtil.createNumberUUID();
		httpPost.setHeader("randomKey", randomKey);
		JSONObject dataObjRe = new JSONObject();
		dataObjRe.put("categoryDir", "book");

		System.out.println(dataObjRe.toString());
		String dataRe = DES3.encode(dataObjRe.toString().getBytes("utf-8"), "c5e110477f7ab35027743d36faf61e3c");
		System.out.println(dataRe.toString());
		httpPost.setHeader("data", dataRe);
		String signature = Md5Util.md5Encode("resource" + "P201704051440251503135" + timestamp + "NjdjNDcx" + "1.0.0"
				+ "2" + randomKey + dataRe + "ZTA3MWZjMGQ0MTliYT");
		httpPost.setHeader("signature", signature);
		MultipartEntityBuilder builder = MultipartEntityBuilder.create();
		builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
		builder.setCharset(CharsetUtils.get("UTF-8"));

		// 上传时生成的临时文件保存目录
		String tempPath = request.getServletContext().getRealPath("/WEB-INF/temp");
		File tmpFile = new File(tempPath);
		if (!tmpFile.exists()) {
			// 创建临时目录
			tmpFile.mkdir();
		}

		// 得到文件保存的名称
		String saveFilename = makeFileName(filename);
		// 得到文件的保存目录
		FileOutputStream out = new FileOutputStream(tempPath + "\\" + saveFilename);
		// 创建一个文件输出流
		// 创建一个缓冲区
		byte buffer[] = new byte[1024];
		// 判断输入流中的数据是否已经读完的标识
		int len = 0;
		// 循环将输入流读入到缓冲区当中，(len=in.read(buffer))>0就表示in里面还有数据
		while ((len = in.read(buffer)) > 0) {
			// 使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\" +
			// filename)当中
			out.write(buffer, 0, len);
		}
		// 关闭输入流
		in.close();
		// 关闭输出流
		out.close();

		File file = new File(tempPath + "\\" + saveFilename);
		FileBody bin = new FileBody(file);
		builder.addPart("image", bin);// uploadFile对应服务端类的同名属性<File类型>

		// StringBody uploadFileName = new StringBody("my.png",
		// Consts.UTF_8);
		// builder.addPart("uploadFileName", uploadFileName);////
		// uploadFileName对应服务端类的同名属性<String类型>
		HttpEntity reqEntity = builder.build();
		httpPost.setEntity(reqEntity);

		CloseableHttpResponse response = httpclient.execute(httpPost);
		HttpEntity entity = response.getEntity();
		String result = EntityUtils.toString(entity, "utf-8");
		String resultDes = DES3.decode(result.getBytes("utf-8"), "c5e110477f7ab35027743d36faf61e3c");
		JSONObject reObj = JSONObject.fromObject(resultDes);
		int reStatus = reObj.optInt("status", 1);
		if (reStatus == 0) {
			JSONObject reDataObj = reObj.optJSONObject("data");
			JSONArray reArray = reDataObj.optJSONArray("fileUrlList");
			if (reArray.size() >= 1) {
				JSONObject fObj = reArray.getJSONObject(0);
//例：http://file.sxyd8.com/P201704051440251503135/photo/book/2017/6/12/8b693dc8a95d43b79bf45f45723c6bfd.jpg
//				imgPath =fObj.optString("fileServer", "") +fObj.optString("filePath", "");
				///例：P201704051440251503135/photo/book/2017/6/12/8b693dc8a95d43b79bf45f45723c6bfd.jpg
				imgPath =fObj.optString("filePath", "");
			}
		}
		//删除临时文件
		file.delete();
		return imgPath;
	}

	public static void inputstreamtofile(InputStream ins, File file) {
		try {
			OutputStream os = new FileOutputStream(file);
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
			os.close();
			ins.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @Method: makeFileName
	 * @Description: 生成上传文件的文件名，文件名以：uuid+"_"+文件的原始名称
	 * @Anthor:孤傲苍狼
	 * @param filename
	 *            文件的原始名称
	 * @return uuid+"_"+文件的原始名称
	 */
	private static String makeFileName(String filename) { // 2.jpg
		// 为防止文件覆盖的现象发生，要为上传文件产生一个唯一的文件名
		return UUID.randomUUID().toString() + "_" + filename;
	}
}
